package com.hzj.config;

import com.hzj.pojo.Users;
import com.hzj.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class StudentRealm extends AuthorizingRealm {
    @Autowired
    UserService us;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==》授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
//        获取认证方法中存入的信息
        Users user = (Users) subject.getPrincipal();
        if (user.getAuthority().equals("admin")) {//设置只有拥有指定权限的的用户才给与权限
            info.addStringPermission("user:add");//添加权限，可以从数据库中查询出用户权限数据，再根据数据内容进行授权
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了==》认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        访问数据库进行比对
        Users user = us.check(token.getUsername());
        if (user == null) {
            return null;
        }

//        密码认证只需要让shiro来做就行，不需要手动,把数据库密码放入就好，可以加密
//        并且可以携带一个Object(比如我携带的是user对象)，获取存入的对象SecurityUtils.getSubject().getPrincipal()，上面授权方法中有使用到
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
